﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NCacheDClient.NCacheDServer;
using NCacheDClient.Exceptions;
using System.ServiceModel;



namespace NCacheDClient.Internal.Clients
{

    internal partial class WCFClient : ICacheClient
    {

        CacheServerClient client = null;

        public WCFClient(CacheServerClient client)
        {
            this.client = client;
        }


        byte[] ICacheClient.Get(string key)
        {
            try
            {
                return client.Get(key);
            }
            catch (System.ServiceModel.CommunicationException ce)
            {
                string errorMessage = string.Format("Error communicating with server '{0}' on port {1}. See inner exception for more details.", client.Endpoint.Address.Uri.Host, client.Endpoint.Address.Uri.Port);
                throw new CacheServerConnectionException(errorMessage, ce);
            }
        }

        void ICacheClient.Put(string key, DateTime expires, byte[] data)
        {
            client.PutAsync(key, expires, data);
        }

        void ICacheClient.Delete(string key)
        {
            client.DeleteAsync(key);
        }

        long ICacheClient.GetSize()
        {
            try
            {
                return client.GetSize();
            }
            catch (System.ServiceModel.CommunicationException ce)
            {
                string errorMessage = string.Format("Error establishing connection to server '{0}' on port {1}. See inner exception for more details.", client.Endpoint.Address.Uri.Host, client.Endpoint.Address.Uri.Port);
                throw new CacheServerConnectionException(errorMessage, ce);
            }
        }

        internal static WCFClient Create(string host, int port)
        {
            NetTcpBinding binding = MakeDefaultBinding();
            var address = new EndpointAddress(string.Format("net.tcp://{0}:{1}/NCacheDServer", host, port));
            CacheServerClient client = new CacheServerClient(binding, address);
            return new WCFClient(client);

        }

        private static NetTcpBinding MakeDefaultBinding()
        {
            NetTcpBinding binding = new NetTcpBinding();
            binding.Security = new NetTcpSecurity();
            binding.Security.Mode = SecurityMode.None;
            binding.MaxBufferPoolSize = 524288;
            binding.MaxBufferSize = 1048576;
            binding.MaxConnections = 10;
            binding.MaxReceivedMessageSize = 1048576;
            binding.ReaderQuotas.MaxArrayLength = 1048576;

            return binding;
        }

    }
}
